/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        while(root!=nullptr)
        {
            //在同侧则还未到最近祖先
            if(root->val<p->val&&root->val<q->val)
            {
                root=root->right;//都在右子树中
            }
            else if(root->val>p->val&&root->val>q->val)
            {
                root=root->left;//都在左子树中
            }
            //异侧或者一个结点为当前结点则找到公共结点
            else
            {
                break;
                
            }
        }
        return root;
    }
};